package com.sanerzone.smscenter.gateway.http.handler.impl;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sanerzone.smscenter.biz.message.SMSMOMessage;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSRTMessage;
import com.sanerzone.smscenter.biz.message.SMSSRMessage;
import com.sanerzone.smscenter.biz.utils.UnicodeUtil;
import com.sanerzone.smscenter.common.tools.HttpRequest;
import com.sanerzone.smscenter.gateway.http.handler.GateWayHttpAbstract;
import com.sanerzone.smscenter.gateway.http.message.SmsHttpMsgResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 福建冠网
 */
public class SmsApiFJGWv2 extends GateWayHttpAbstract
{

    public SmsApiFJGWv2(String gateWayID, String jsonParams)
    {
        super(gateWayID, jsonParams);
    }

    @Override
    public List<SMSSRMessage> doSend(SMSMTMessage mt) {
        String json = "";
        List<SMSSRMessage> resultList = Lists.newArrayList();

        SMSSRMessage message = new SMSSRMessage();
        message.setPhones(mt.getPhone());
        message.setMessage( mt );
        message.setFailPhone("");
        message.setResult("0");
        message.setMsgid("test12345");
        resultList.add(message);
        return resultList;

    }
    
    @Override
    public SmsHttpMsgResponse parseReport(String text, List<SMSRTMessage> rtList)
    {
        if (StringUtils.isNotBlank(text)) {
            Document docuResult;
            try {
                docuResult = DocumentHelper.parseText(text);
                Element root = docuResult.getRootElement();
                if (StringUtils.contains(text,"statusbox")) {
                    logger.info("{}网关推送状态报告:{}", gateWayID, text);
                    List<Element> itemElements = root.elements("statusbox");
                    for (Element data : itemElements) {
                        SMSRTMessage smsRtMessage = initSmsRtMessage(data.element("taskid").getStringValue(), data.element("mobile").getStringValue(), data.element("mobile").getStringValue(),
                                data.element("status").getStringValue(), "10");
                        rtList.add(smsRtMessage);
                    }
                }
            } catch (DocumentException e) {
                e.printStackTrace();
                logger.error("状态异步获取解析失败，{}网关推送状态报告:{}", gateWayID, text);
            }
        }
        return new SmsHttpMsgResponse("success");
    }

    @Override
    public SmsHttpMsgResponse parseDeliver(String text, List<SMSMOMessage> moList)
    {
        SmsHttpMsgResponse smsHttpMsgResponse = new SmsHttpMsgResponse("0");
        if (StringUtils.isNotBlank(text)) {
            Document docuResult;
            try {
                docuResult = DocumentHelper.parseText(text);
                Element root = docuResult.getRootElement();
                if (StringUtils.contains(text,"callbox")) {
                    logger.info("{}网关推送用户上行:{}", gateWayID, text);
                    List<Element> itemElements = root.elements("callbox");
                    for (Element data : itemElements) {
                        SMSMOMessage sMSMOMessage = new SMSMOMessage();
                        sMSMOMessage.setGateWayID(gateWayID);
                        sMSMOMessage.setMsgContent(UnicodeUtil.decode(data.element("content").getStringValue()));
                        sMSMOMessage.setMsgid(root.element("taskid").getStringValue());
                        sMSMOMessage.setPhone(data.element("mobile").getStringValue());
                        sMSMOMessage.setSenttime(data.element("receivetime").getStringValue());
//                sMSMOMessage.setSpnumber(String.valueOf(resultMap.get("srcid")));
                        sMSMOMessage.setUuid(UUID.randomUUID().toString());
                        moList.add(sMSMOMessage);
                    }
                }
            } catch (DocumentException e) {
                e.printStackTrace();
                logger.error("状态异步获取解析失败，{}网关推送状态报告:{}", gateWayID, text);
            }
        }
        return smsHttpMsgResponse;
    }

    @Override
    public String queryReport(String jsonText) {
        Map<String,String> params = Maps.newHashMap();
        String t = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        params.put("userid",paramsMaps.get("userid"));
        params.put("timestamp",t);
        params.put("statusNum",paramsMaps.get("statusNum"));
        params.put("action","query");
        params.put("sign",DigestUtils.md5Hex(paramsMaps.get("account") + paramsMaps.get("passwd") + t));
        String result =  HttpRequest.sendGet(paramsMaps.get("apiUrl") + "/v2statusApi.aspx", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
//        logger.info("{}网关主动查询状态报告:{}", gateWayID, result);
        if (result.contains("statusbox"))
            return result;
        return "";
    }

    @Override
    public String queryDeliver(String jsonText) {
        String t = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        Map<String,String> params = Maps.newHashMap();
        params.put("userid",paramsMaps.get("userid"));
        params.put("timestamp",t);
        params.put("sign",paramsMaps.get("account") + paramsMaps.get("passwd") + t);
        params.put("action","query");
        String result =  HttpRequest.sendGet(paramsMaps.get("apiUrl") + "/v2callApi.aspx", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        if (result.contains("callbox"))
            return result;
        return "";
    }

    /**
     *
     * userid 用户名
     * account 账号
     * password 密码
     * action 任务名称 固定值overage
     * @return
     */
    public String balance()
    {
        Map<String,Object> params = Maps.newHashMap();
        String t = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        params.put("userid",paramsMaps.get("userid"));
        params.put("timestamp",t);
        params.put("action","overage");
        String preSign = paramsMaps.get("account") + paramsMaps.get("passwd") + t;
        params.put("sign", DigestUtils.md5Hex(preSign));
        String result =  HttpRequest.sendGet(paramsMaps.get("apiUrl") + "/v2sms.aspx" , Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        System.out.println(result);
        logger.info("余额查询网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);
        Document  docuResult;
        try{
            docuResult  = DocumentHelper.parseText(result);
            Element root = docuResult.getRootElement();
            root.getStringValue();
            if (StringUtils.equals("Sucess",root.element("returnstatus").getStringValue())) {
                return "余额：" + root.element("overage").getStringValue() + ",点数：" + root.element("sendTotal").getStringValue();
            }
        }catch (DocumentException e){
            e.printStackTrace();
            logger.error("余额查询xml解析失败，网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);
            return "余额查询解析错误";
        }
        return "余额查询失败";
    }
    
    public static void main(String[] args)
    {
        String params = "{\"userid\":\"13\",\"account\":\"qianxiang\",\"passwd\":\"qianxiang\",\"apiUrl\":\"http://39.107.53.239:8088\",\"statusNum\":\"4000\"}";
        SmsApiFJGWv2 api = new SmsApiFJGWv2("ZY",params);
//        String balance = api.balance();
        SMSMTMessage message = new SMSMTMessage();
        message.setPhone("18268846802");
        message.setId("test123456");
        message.setSmsContent("【千橡科技】你的短信验证码是123456");
//        api.doSend(message);
        api.queryReport("");
//        System.out.println(DigestUtils.md5Hex("testmima20120701231212"));
    }
    
}